﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MobileDesigner.Models;
using WebMatrix.WebData;
using System.Xml;
using System.IO;
using System.Xml.Linq;
using System.Web.Helpers;

namespace MobileDesigner.Controllers
{
    public class ProjectController : Controller
    {
        private MobileDesignerContext db = new MobileDesignerContext();
        private string defaultXmlLocation = "~/App_Data/defaultApp.xml";

        //
        // GET: /Project/

        public ActionResult Index()
        {
            var projects = from p in db.Projects
                           join pa in db.ProjectAssociates on p.ID equals pa.ProjectID
                           join u in db.Users on pa.UserID equals WebSecurity.CurrentUserId
                           where u.ID == pa.UserID
                           select new ProjectListModel { ID = p.ID, Name = p.Name, Description = p.Description };
            return View(projects.ToList());
        }

        //
        // GET: /Project/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Project/Create

        [HttpPost]
        public ActionResult Create(ProjectListModel project)
        {
            if (ModelState.IsValid)
            {
                CreateFolderIfNeeded("~/App_Data/" + User.Identity.Name);
                Project newProject = new Project()
                {
                    Name = project.Name,
                    Description = project.Description,
                    Location = "~/App_Data/" + User.Identity.Name + "/" + project.Name + ".xml"
                };
                if (System.IO.File.Exists(newProject.Location))
                    return View(project);
                db.Projects.Add(newProject);
                db.SaveChanges();
                ProjectAssociate associtate = new ProjectAssociate() { UserID = WebSecurity.CurrentUserId, ProjectID = db.Projects.Where(p => p.Location == newProject.Location).FirstOrDefault().ID };
                db.ProjectAssociates.Add(associtate);
                db.SaveChanges();
                int projectId = (from p in db.Projects
                                 join pa in db.ProjectAssociates on p.ID equals pa.ProjectID
                                 where pa.UserID == WebSecurity.CurrentUserId && p.Name == newProject.Name
                                 select p).FirstOrDefault().ID;
                return RedirectToAction("Constructor", new { id = projectId});
            }
            return View(project);
        }

        //
        //POST : /Project/Save

        [HttpPost]
        public ActionResult Save(ProjectMapModel projectToSave)
        {
            string projectLocation = (from p in db.Projects
                                      join pa in db.ProjectAssociates on p.ID equals pa.ProjectID
                                      where p.Name == projectToSave.Name && pa.UserID == WebSecurity.CurrentUserId
                                      select p).FirstOrDefault().Location;
            System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(ProjectMapModel));
            System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath(projectLocation));
            writer.Serialize(file, projectToSave);
            file.Close();
            return Json(new { redirectUrl = Url.Action("Index", "Project"), isRedirect = true });
        }

        //
        // GET: /Project/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Project project = db.Projects.Find(id);
            if (project == null)
            {
                return HttpNotFound();
            }
            return RedirectToAction("Constructor", new { id = id });
        }

        //
        // GET: /Project/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Project project = db.Projects.Find(id);
            if (project == null)
            {
                return HttpNotFound();
            }
            return View(new ProjectListModel { ID = project.ID, Description = project.Description, Name = project.Name });
        }

        //
        // POST: /Project/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Project project = db.Projects.Find(id);
            System.IO.File.Delete(Server.MapPath(project.Location));
            db.Projects.Remove(project);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        // GET: /Project/Constructor/5
        public ActionResult Constructor(int id = 0)
        {
            string xmlLocation;
            var project = (from pa in db.ProjectAssociates
                          join p in db.Projects on pa.ProjectID equals p.ID
                          where p.ID == id && WebSecurity.CurrentUserId == pa.UserID
                          select new { Name = p.Name, Description = p.Description, Location = p.Location }).FirstOrDefault();
            if (System.IO.File.Exists(Server.MapPath(project.Location)))
                xmlLocation = Server.MapPath(project.Location);
            else
                xmlLocation = Server.MapPath(defaultXmlLocation);
            System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(ProjectMapModel));
            System.IO.StreamReader file = new System.IO.StreamReader(xmlLocation);
            ProjectMapModel projectMap = new ProjectMapModel();
            projectMap = (ProjectMapModel)reader.Deserialize(file);
            file.Close();
            return View(projectMap);
        }

        [HttpPost]
        public virtual ActionResult UploadFile()
        {
            HttpPostedFileBase myFile = Request.Files["MainImage"];
            bool isUploaded = false;
            string message = "File upload failed";

            if (myFile != null && myFile.ContentLength != 0)
            {
                string pathForSaving = Server.MapPath("~/App_Data/" + User.Identity.Name + "/Uploads");
                if (this.CreateFolderIfNeeded(pathForSaving))
                {
                    try
                    {
                        myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName));
                        isUploaded = true;
                        message = "File uploaded successfully!";
                    }
                    catch (Exception ex)
                    {
                        message = string.Format("File upload failed: {0}", ex.Message);
                    }
                }
            }
            return Json(new { isUploaded = isUploaded, message = message }, "text/html");
        }

        private bool CreateFolderIfNeeded(string path)
        {
            bool result = true;
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception)
                {
                    result = false;
                }
            }
            return result;
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}